// imports
const { ethers, run, network } = require('hardhat');

async function main() {
    console.log('Deploying to network:', network.name);

    const simpleStorageFactory =
        await ethers.getContractFactory('SimpleStorage');

    console.log('Deploying SimpleStorage...');
    const simpleStorageContract = await simpleStorageFactory.deploy();

    await simpleStorageContract.waitForDeployment();
    console.log(`Deployed contract to: ${simpleStorageContract.target}`);

    // Verify contract
    // 1 == 1 -> true
    // 1 == "1" -> true
    // 1 === 1 -> true
    // 1 === "1" -> false
    if (network.config.chainId === 11155111 && process.env.ETHERSCAN_API_KEY) {
        console.log('Waiting for block confirmations...');

        // Not functionable in version 6^ ethers ----->

        await simpleStorageContract.deploymentTransaction().wait(6);
        await verify(simpleStorageContract.target, []);

        //______________________________________________
    }

    const currentFavoriteNumber = await simpleStorageContract.retrieve();
    console.log(`Current favorite number: ${currentFavoriteNumber.toString()}`);

    const transactionResponse = await simpleStorageContract.store(13);
    await transactionResponse.wait(1);
    const updatedFavoriteNumber = await simpleStorageContract.retrieve();
    console.log(`Updated favorite number: ${updatedFavoriteNumber}`);
}

// async function verify(contractAddress, args) {
const verify = async function verify(contractAddress, args) {
    console.log('Verifying contract...');

    try {
        await run('verify:verify', {
            address: contractAddress,
            constructorArguments: args,
        });
    } catch (error) {
        if (error instanceof Error) {
            if (error.message.toLowerCase().includes('already verified')) {
                console.log('Contract already verified');
            }
            console.error('Failed to verify contract:', error.message || error);
        } else {
            console.error('Unexpected error:', error);
        }
    }
};

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error);
        process.exit(1);
    });
